package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.Act;
import com.ruoyi.system.domain.ActCategory;
import com.ruoyi.system.domain.ActTitle;
import com.ruoyi.system.domain.Game;
import com.ruoyi.system.dto.ResultDto;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.ActVO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 参赛作品Controller
 *
 * @author ruoyi
 * @date 2021-11-28
 */
@Controller
@RequestMapping("/system/act")
public class ActController extends BaseController
{
    private String prefix = "system/act";

    @Autowired
    private IActService actService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IActTitleService actTitleService;

    @Autowired
    private IGameService gameService;

    @Autowired
    private IActCategoryService actCategoryService;

    @Value("${ruoyi.actTemplateName:作品模版}")
    private String actTemplateName;

    @Value("${ruoyi.actExportName:作品汇总}")
    private String actExportName;

    @RequiresPermissions("system:act:view")
    @GetMapping()
    public String act(ModelMap mmap)
    {
        List<Game> games = gameService.selectDefault();
        mmap.put("games",games);

        boolean canOperation = getUserOperationPower();
        if(!canOperation){
            SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
            if(dept == null){
                return null;
            }
            if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
                canOperation = true;
            }
        }
        mmap.put("canOperation",canOperation);
        return prefix + "/act";
    }

    /**
     * 查询参赛作品列表
     */
    @RequiresPermissions("system:act:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Act act)
    {
        SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
        if(dept == null){
            return null;
        }
        act.setCurUser(getSysUser().getLoginName());
        if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
            act.setAllSelectPerm(true);
        }
        //查询用户所在的学院
        if(act.isAllSelectPerm() == false){
            SysDept curUserFaculty = sysDeptService.getUserFaculty(getSysUser());
            if(curUserFaculty != null){
                act.setCurUserFacultyId(curUserFaculty.getDeptId());
            }else{
                return null;
            }
        }
        startPage();
        List<Act> list = actService.selectActList(act,getSysUser());
        return getDataTable(list);
    }

    /**
     * 导出参赛作品列表
     */
    @RequiresPermissions("system:act:export")
    @Log(title = "参赛作品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Act act)
    {
        SysDept dept = sysDeptService.selectDeptById(getSysUser().getDeptId());
        if(dept == null){
            return null;
        }
        act.setCurUser(getSysUser().getLoginName());
        if(dept.getAncestors().startsWith("0,100") || dept.getDeptId().intValue() == 100){
            act.setAllSelectPerm(true);
        }
        //查询用户所在的学院
        if(act.isAllSelectPerm() == false){
            SysDept curUserFaculty = sysDeptService.getUserFaculty(getSysUser());
            if(curUserFaculty != null){
                act.setCurUserFacultyId(curUserFaculty.getDeptId());
            }else{
                return null;
            }
        }
        List<Act> list = actService.selectActList(act,getSysUser());
        if(list != null && list.size()>0){
            for(Act item : list){
                String schoolName = item.getSchool();
                String beginChar = schoolName.substring(0,1);
                if("0123456789".indexOf(beginChar) > -1){
                    String begin = schoolName.substring(0,6);
                    begin = begin.replaceAll("[0-9|-]","");
                    schoolName = begin + schoolName.substring(6);
                }
                item.setSchool(schoolName);
            }
        }
        ExcelUtil<Act> util = new ExcelUtil<Act>(Act.class);
        return util.exportExcel(list, this.actExportName);
    }

    /**
     * 新增参赛作品
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        // 获取当前用户的学校和院系
        //getUserId()
        SysDept school = sysDeptService.getUserSchools(getSysUser());
        if(school != null){
            String schoolName = school.getDeptName();
            String beginChar = schoolName.substring(0,1);
            if("0123456789".indexOf(beginChar) > -1){
                String begin = schoolName.substring(0,6);
                begin = begin.replaceAll("[0-9|-]","");
                schoolName = begin + schoolName.substring(6);
            }
            school.setDeptName(schoolName);
        }
        mmap.put("school",school);
        SysDept faculty = sysDeptService.getUserFaculty(getSysUser());
        if(faculty != null && !faculty.getAncestors().equals("0,101") && faculty.getAncestors().startsWith("0,101")){
            mmap.put("faculty",faculty);
        }else{
            mmap.put("faculty",null);
        }
        mmap.put("curDeptId",getSysUser().getDeptId());
        mmap.put("hasPermission",sysDeptService.isUserHasPermission(getSysUser()));
        List<Game> games = gameService.selectDefault();
        if(games !=null && games.size() >0){
            Long gameId = games.get(0).getId();
            List<ActCategory> categories = actCategoryService.findWholeTree();
            ActCategory actCategory = null;
            if(categories != null && categories.size()>0){
                for(ActCategory item: categories){
                    if(item.hasChildren()){
                        actCategory = item.getChildren().get(0);
                    }else{
                        actCategory = item;
                    }
                    break;
                }
                Long categoryId = actCategory.getId();
                List<ActTitle> actTitles = actTitleService.selectByGameIdAndCategoryId(gameId,categoryId);
                mmap.put("categoryTree",categories);
                mmap.put("actTitles",actTitles);
                mmap.put("games",games);
                return prefix + "/add";
            }
        }

        mmap.put("actTitles",null);
        mmap.put("games",null);
        mmap.put("categoryTree",null);
        return prefix + "/add";
    }

    /**
     * 新增保存参赛作品
     */
    @RequiresPermissions("system:act:add")
    @Log(title = "参赛作品", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Act act)
    {
        //校验actNo是否存在
        boolean isExistActNo = actService.isExistActNo(act.getActNo(),act.getGameId(),null);
        if(isExistActNo){
            return AjaxResult.error("参赛编号的作品已经存在，请重新输入！");
        }
        // 校验院系是否正确
        SysDept sysDept = sysDeptService.selectDeptById(act.getFacultyId());
        if(sysDept == null || sysDept.getAncestors().equals("0,101") || sysDept.getAncestors().startsWith("0,101") == false
            ){
            return AjaxResult.error("请选择正确的院系！");
        }

        act.setCreateBy(getLoginName());
        return toAjax(actService.insertAct(act));
    }

    /**
     * 修改参赛作品
     */
    @RequiresPermissions("system:act:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Act act = actService.selectActById(id);
        List<ActCategory> categories = actCategoryService.findWholeTree();
        List<ActTitle> titles = null;
        if(act != null){
            String schoolName = act.getSchool();
            String beginChar = schoolName.substring(0,1);
            if("0123456789".indexOf(beginChar) > -1){
                String begin = schoolName.substring(0,6);
                begin = begin.replaceAll("[0-9|-]","");
                schoolName = begin + schoolName.substring(6);
            }
            act.setSchool(schoolName);

            Long gameId = act.getGameId();
            Long categoryId = act.getCategoryId();
            if(gameId!= null && categoryId != null){
                List<ActTitle> actTitles = actTitleService.selectByGameIdAndCategoryId(gameId,categoryId);
                mmap.put("titles",actTitles);
            }else{
                mmap.put("titles",null);
            }
        }else{
            mmap.put("titles",null);
        }
        mmap.put("categoryTree",categories);
        mmap.put("act", act);
        return prefix + "/edit";
    }

    /**
     * 修改保存参赛作品
     */
    @RequiresPermissions("system:act:edit")
    @Log(title = "参赛作品", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Act act)
    {
        //校验actNo是否存在
        boolean isExistActNo = actService.isExistActNo(act.getActNo(),act.getGameId(),act.getId());
        if(isExistActNo){
            return AjaxResult.error("参赛编号的作品已经存在，请重新输入！");
        }
        act.setUpdateBy(getLoginName());
        return toAjax(actService.updateAct(act));
    }

    /**
     * 删除参赛作品
     */
    @RequiresPermissions("system:act:remove")
    @Log(title = "参赛作品", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(actService.deleteActByIds(ids));
    }


    /**
     * 导出模版
     * @return
     */
    @RequiresPermissions("system:act:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<ActVO> util = new ExcelUtil<ActVO>(ActVO.class);
        //获取作品类别
        List<Game> games = gameService.selectDefault();
        List<ActCategory> categories = null;
        Map<String,List<String>> map = new HashMap<>();
        List<String> categoryNames = new ArrayList<>();
        if(games !=null && games.size() >0){
            Long gameId = games.get(0).getId();
            categories = actCategoryService.findTreeLeaf();
            if(categories != null && categories.size()>0){
                for(ActCategory actCategory: categories){
                    categoryNames.add(actCategory.getName());
                    List<ActTitle> actTitles = actTitleService.selectByGameIdAndCategoryId(gameId,actCategory.getId());
                    List<String> actNames = null;
                    if(actTitles != null && actTitles.size() >0){
                        actNames = new ArrayList<>();
                        for(ActTitle actTitle: actTitles){
                            actNames.add(actTitle.getTitle());
                        }
                    }
                    map.put(actCategory.getName(),actNames);
                }
            }
        }



        //获取命题
        return util.importActTemplateExcel(this.actTemplateName,map,categoryNames);
        //return util.importTemplateExcel(this.actTemplateName);
    }


    @Log(title = "参赛作品", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:act:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, Long gameId) throws Exception
    {
        if(gameId == null || gameId <= 0){
            return AjaxResult.error("请选择大赛名称");
        }
        ExcelUtil<ActVO> util = new ExcelUtil<ActVO>(ActVO.class);
        List<ActVO> actVos = util.importExcel(file.getInputStream());
        if(actVos == null || actVos.size() == 0){
            return AjaxResult.error("导入的数据为空");
        }

        ResultDto resultDto = actService.importActData(actVos,gameId,getSysUser());
        if(resultDto.isSuccess()){
            String message = "导入成功";
            return AjaxResult.success(message);
        }else{
            return AjaxResult.error(resultDto.getMessage());
        }
    }

    @Autowired
    private ISysConfigService configService;

    private boolean getUserOperationPower(){
        String dateStr = configService.selectConfigByKey("game.end.time");
        if(StringUtils.isNotBlank(dateStr)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try{
                Date  endTime = sdf.parse(dateStr);
                Date now = new Date();
                if(now.compareTo(endTime) >= 0){
                    return false;
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }
        return  true;
    }
}
